package com.byinsight.web.actions;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.byinsight.web.actions.util.UserTokenEncoder;

import eg.backend.base.ContextHolder;

@Component
public class ContextHolderFilter extends OncePerRequestFilter {
	@Autowired
	private ContextHolder contextHolder;
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//get userToken for each request. 
		//validate userToken may also be done here (as security filter)
		//or use a special filter for it
		String token = request.getParameter("userToken");
		if(token != null) {
			contextHolder.setUserId(UserTokenEncoder.getId(token));
			contextHolder.setUserName(UserTokenEncoder.getUsername(token));
		}
		contextHolder.setRequest(request);
		contextHolder.setResponse(response);
		filterChain.doFilter(request, response);		
	}

	public ContextHolder getContextHolder() {
		return contextHolder;
	}

	public void setContextHolder(ContextHolder contextHolder) {
		this.contextHolder = contextHolder;
	}
	
	
}